﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using SherlockGUI.CFG;
using IpeEngCtrlLib;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using SherlockGUI.Dlg;
using SherlockGUI.Log;
using System.IO;

namespace SherlockGUI
{
    public partial class GUI : Form
    {
        
        IpeEngCtrlLib.Engine m_VisionSystem;
        IpeEngCtrlLib.I_ENG_ERROR m_iReturn;
        //系统运行时间
        Stopwatch m_SysRunTime = new Stopwatch();
        
        //运行完成次数
        UInt32 m_uiRunCompleteCount = 0;

        //保存图片路径
        private ArrayList m_PicPathList_OK = new ArrayList();
        private ArrayList m_PicPathList_NG = new ArrayList();

        //是否已经成功初始化。
        bool m_bInit = false;

        bool m_bStop = false;

        //ROI名称用于comboBox_ROI
        //用于鼠标设置ROI
        bool m_bLButtonDown = false;
        string[] m_strROINameList_Show = { "一维码", "二维码"};
        string[] m_strROINameList_Sherlock = { "RectA", "RectB" };

        //
        LoadShowDlg m_LoadShowDlg = new LoadShowDlg();


        public GUI()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 界面显示委托
        /// </summary>
        /// <param name="lbl"></param>
        /// <param name="strText"></param>
        private delegate void setTextCallback_Label(Label lbl, string strText);
        private void setText_Label(Label lbl, string strText)
        {
            if (lbl.InvokeRequired)
            {
                setTextCallback_Label d = new setTextCallback_Label(setText_Label);
                lbl.Invoke(d, lbl, strText);
            }
            else
            {
                lbl.Text = strText;
                lbl.Refresh();
            }
        }
        private delegate void setTextCallback_PictureBox(PictureBox lbl, string strText);
        private void setText_PictureBox(PictureBox lbl, string strText)
        {
            if (lbl.InvokeRequired)
            {
                setTextCallback_PictureBox d = new setTextCallback_PictureBox(setText_PictureBox);
                lbl.Invoke(d, lbl, strText);
            }
            else
            {
                lbl.Text = strText;
                lbl.Refresh();
            }
        }
        private delegate void setTextCallback_TextBox(TextBox lbl, string strText);
        private void setText_TextBox(TextBox lbl, string strText)
        {
            if (lbl.InvokeRequired)
            {
                setTextCallback_TextBox d = new setTextCallback_TextBox(setText_TextBox);
                lbl.Invoke(d, lbl, strText);
            }
            else
            {
                lbl.Text = strText;
                lbl.Refresh();
            }
        }
        private delegate void setColorCallback_PictureBox(PictureBox lbl, Color picBoxColor);
        private void setColor_PictureBox(PictureBox picBox, Color picBoxColor)
        {
            if (picBox.InvokeRequired)
            {
                setColorCallback_PictureBox d = new setColorCallback_PictureBox(setColor_PictureBox);
                picBox.Invoke(d, picBox, picBoxColor);
            }
            else
            {
                //   picBox.BackColor = picBoxColor;
                picBox.Refresh();
            }
        }

        private delegate void setColorCallback_Label(Label lbl, Color picBoxColor);
        private void setColor_Label(Label picBox, Color picBoxColor)
        {
            if (picBox.InvokeRequired)
            {
                setColorCallback_Label d = new setColorCallback_Label(setColor_Label);
                picBox.Invoke(d, picBox, picBoxColor);
            }
            else
            {
                picBox.BackColor = picBoxColor;
                picBox.Refresh();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        public void SetExportTime(double dTime)
        {
            m_VisionSystem.VarSetDouble("iExposureTime", dTime);
            m_VisionSystem.VarSetBool("bSetExposureTime", true);
        }

        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }


        private void SavePic(bool bInspPassResult)
        {
            if (GlobalCfg.m_LogCfg.PicLogCfg_NG.bSavePic == true && bInspPassResult == false)
            {
                string strFileName = GlobalCfg.m_LogCfg.PicLogCfg_NG.strPicPath + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".bmp";
                m_PicPathList_NG.Add(strFileName);

                m_iReturn = m_VisionSystem.SoImageSaveWithGraphics(GlobalCfg.m_SherlockCfg.strImgWindowsName, strFileName);
            }
            else if (GlobalCfg.m_LogCfg.PicLogCfg_OK.bSavePic == true && bInspPassResult == true)
            {
                string strFileName = GlobalCfg.m_LogCfg.PicLogCfg_OK.strPicPath + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".bmp";
                m_PicPathList_OK.Add(strFileName);

                m_iReturn = m_VisionSystem.SoImageSaveWithGraphics(GlobalCfg.m_SherlockCfg.strImgWindowsName, strFileName);
            }

            try
            {
                if (m_PicPathList_NG.Count > GlobalCfg.m_LogCfg.PicLogCfg_NG.iMaxPicNum)
                {
                    File.Delete(m_PicPathList_NG[0].ToString());
                    m_PicPathList_NG.RemoveAt(0);
                }
                if (m_PicPathList_OK.Count > GlobalCfg.m_LogCfg.PicLogCfg_OK.iMaxPicNum)
                {
                    File.Delete(m_PicPathList_OK[0].ToString());
                    m_PicPathList_OK.RemoveAt(0);
                }
            }
            catch (System.Exception )
            {

            }
        }


        private void VisionSystem_RunStop()
        {
            SysLog.WriteInfoLog("GUI", "VisionSystem_RunStop");

            //setText_Label(label_CheckResult, "停止检测");
            //setColor_Label(label_CheckResult, System.Drawing.Color.Yellow);
        }

        private void VisionSystem_RunError(IpeEngCtrlLib.I_EXEC_ERROR nError)
        {

            SysLog.WriteInfoLog("GUI", "VisionSystem_RunError:" +  nError);

            bool bState = false;
            string strMsg;
            switch (nError)
            {
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_ROI_OUTSIDE:
                    bState = true;
                    strMsg = "ROI 超出图片范围";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_UNKNOWN_ERROR:
                    strMsg = "相机出现未知错误，请检查相机是否运行正常，网线是否正常";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_IO_NOT_CONNECTED:
                    strMsg = "相机I/O没有连接";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_STOP:
                    strMsg = "相机停止运行";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_SCRIPT_ERROR:
                    strMsg = "相机程序运行出错";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_TIMEOUT:
                default:	//I_EXEC_OK	--  --
                    bState = true;
                    strMsg = "相机运行正常";
                    break;
            }
            if (!bState)
            {
                setText_Label(label_CheckResult, strMsg);
                setColor_Label(label_CheckResult, System.Drawing.Color.Yellow);
            }
        }

        private void VisionSystem_RunCompleted()
        {
            //总运行次数
            m_uiRunCompleteCount++;
            //textBox_RunCompleteCount.Text = m_uiRunCompleteCount.ToString();
            setText_TextBox(textBox_RunCompleteCount, m_uiRunCompleteCount.ToString());
            ;
            //检测耗时
            double dTimeCost;
            m_iReturn = m_VisionSystem.VarGetDouble("dTimeCost_Out", out dTimeCost);
            //textBox_CheckTime.Text = dTimeCost.ToString("F");
            setText_TextBox(textBox_CheckTime, dTimeCost.ToString("F2"));

            double dPass;
            double dFail;
            bool bInspPassResult;
            m_iReturn = m_VisionSystem.VarGetDouble("dOKCount_Out", out dPass);
            m_iReturn = m_VisionSystem.VarGetDouble("dNGCount_Out", out dFail);

            ShowInspectCount(dPass, dFail);

            m_iReturn = m_VisionSystem.VarGetBool("bResult_Out", out bInspPassResult);
            if (bInspPassResult == true)  //  
            {
                setText_Label(label_CheckResult, "OK");
                setColor_Label(label_CheckResult, System.Drawing.Color.LightGreen);
            }
            else if (bInspPassResult == false) // 
            {
                setText_Label(label_CheckResult, "NG");
                setColor_Label(label_CheckResult, System.Drawing.Color.Tomato);
            }

            SavePic(bInspPassResult);
            SaveResultCount();
        }

        private void InitSherlock()
        {
            m_bInit = false;

            string strSrc = GlobalCfg.m_SherlockCfg.strProgramPath;

            try
            {
                if (System.IO.File.Exists(strSrc) == false)
                {
                    strSrc = "";
                }

                strSrc = System.IO.Path.GetDirectoryName(strSrc);
            }
            catch (System.Exception)
            {

            }

            if (strSrc.Length < 1)
            {
                setText_Label(label_CheckResult, "没有找到Sherlock目录");
                setColor_Label(label_CheckResult, System.Drawing.Color.Yellow);
            }
            else if (strSrc.Length < 4)
            {
                setText_Label(label_CheckResult, "Sherlock 程序不能放在根目录下");
                setColor_Label(label_CheckResult, System.Drawing.Color.Yellow);
            }
           

            //Make sure to dispose the VisionSystem object in Dispose which is shown in this example
            SysLog.WriteInfoLog("GUI","m_VisionSystem.EngInitialize");

            m_LoadShowDlg.SetNotifyInfo(60, "开始加载检测引擎...");
            System.Windows.Forms.Application.DoEvents();

            m_VisionSystem = new IpeEngCtrlLib.Engine();
            if (GlobalCfg.m_SherlockCfg.strDrivers.Length > 0)
            {
                m_VisionSystem.EngSetAcqIni(GlobalCfg.m_SherlockCfg.strDrivers);
            }
            m_iReturn = m_VisionSystem.EngInitialize();
            if (m_iReturn != IpeEngCtrlLib.I_ENG_ERROR.I_OK)
            {
                MessageBox.Show("加载检测引擎失败...", "FATAL ERROR", MessageBoxButtons.OK);

                SysLog.WriteErrorLog("GUI", "Could not initialize VisionSystem object");
                Close();
            }

            // VisionSystem RunCompleted event handler definition
            m_VisionSystem.RunCompleted +=
                 new IpeEngCtrlLib._IEngineEvents_RunCompletedEventHandler(VisionSystem_RunCompleted);

            m_VisionSystem.RunStop +=
                 new IpeEngCtrlLib._IEngineEvents_RunStopEventHandler(VisionSystem_RunStop);

            m_VisionSystem.OnRunError +=
                 new IpeEngCtrlLib._IEngineEvents_OnRunErrorEventHandler(VisionSystem_RunError);

            if (File.Exists(GlobalCfg.m_SherlockCfg.strProgramPath) != true)
            {
                MessageBox.Show(GlobalCfg.m_SherlockCfg.strProgramPath, "没有找到Sherlock程序");
                SysLog.WriteErrorLog("GUI", "没有找到Sherlock程序[{0}]");
                return;
            }

            m_LoadShowDlg.SetNotifyInfo(70, "加载视觉程序...");
            System.Windows.Forms.Application.DoEvents();

            SysLog.WriteInfoLog("GUI", "加载视觉程序[{0}]");
            m_iReturn = m_VisionSystem.InvLoad(GlobalCfg.m_SherlockCfg.strProgramPath);

            axIpeDspCtrl_Sherlock.ConnectEngine(m_VisionSystem.GetEngineObj());// connect display object to the VisionSystem object


            m_LoadShowDlg.SetNotifyInfo(90, "开始加载窗口...");
            System.Windows.Forms.Application.DoEvents();

            //
            SysLog.WriteInfoLog("GUI", "ConnectImgWindow[{0}");
            int iRet = axIpeDspCtrl_Sherlock.ConnectImgWindow(GlobalCfg.m_SherlockCfg.strImgWindowsName);// connect display to VisionSystem image window

            //
            axIpeDspCtrl_Sherlock.SetZoom(GlobalCfg.m_SherlockCfg.dPicZoom);// set display zoom to stretch

            m_bInit = true;
        }

        private void FInitSherlock()
        {
            Stop();

            //先停止
            m_VisionSystem.CamAcqAbort();

            m_VisionSystem.EngTerminate();

            //
            axIpeDspCtrl_Sherlock.DisconnectImgWindow();//disconnect display window
            //
        }

        private void LoadPicLog()
        {
            try
            {
                string[] files = Directory.GetFiles(GlobalCfg.m_LogCfg.PicLogCfg_NG.strPicPath);
                foreach (string formFileName in files)
                {
                    m_PicPathList_NG.Add(formFileName);
                }

                string[] files_OK = Directory.GetFiles(GlobalCfg.m_LogCfg.PicLogCfg_OK.strPicPath);
                foreach (string formFileName in files_OK)
                {
                    m_PicPathList_OK.Add(formFileName);
                }
            }
            catch (Exception)
            {

            }
        }

        bool Init()
        {
            SysLog.WriteInfoLog("GUI", "Init");

            //系统总运行时间
            m_SysRunTime.Start();

            //加载配置
            GlobalCfg.LoadCfg();

            //加载所有的旧图片            
            if (GlobalCfg.m_LogCfg.PicLogCfg_NG.bSavePic == true || GlobalCfg.m_LogCfg.PicLogCfg_OK.bSavePic == true)
            {
                LoadPicLog();
            }

            //是否保存图片
            if (GlobalCfg.m_LogCfg.PicLogCfg_NG.bSavePic == true)
            {
                Menu_SaveNGPic.Checked = true;
            }
            else
            {
                Menu_SaveNGPic.Checked = false;
            }
            if (GlobalCfg.m_LogCfg.PicLogCfg_OK.bSavePic == true)
            {
                Menu_SaveOKPic.Checked = true;
            }
            else
            {
                Menu_SaveOKPic.Checked = false;
            }

            //
            InitSherlock();

            //
            if (GlobalCfg.m_LogCfg.InspectCount.bSaveCount)
            {
                
            }
            else
            {
                GlobalCfg.m_LogCfg.InspectCount.iOKCount = 0;
                GlobalCfg.m_LogCfg.InspectCount.iNGCount = 0;
            }
            ShowInspectCount(GlobalCfg.m_LogCfg.InspectCount.iOKCount, GlobalCfg.m_LogCfg.InspectCount.iNGCount);
            if (m_bInit == true)
            {
                m_VisionSystem.VarSetDouble("dOKCount_Out", GlobalCfg.m_LogCfg.InspectCount.iOKCount);
                m_VisionSystem.VarSetDouble("dNGCount_Out", GlobalCfg.m_LogCfg.InspectCount.iNGCount);
            }


            //ROI Name
            if (comboBox_ROI.Items.Count > 0)
            {
                comboBox_ROI.Items.Clear();
            }
            comboBox_ROI.Items.AddRange(m_strROINameList_Show);
            comboBox_ROI.SelectedIndex = 0;

            if (GlobalCfg.m_SysCfg.bAutoRun == true)
            {
                Menu_Continuous_Click(null, null);
            }
            else
            {
                Menu_Halt_Click(null, null);
            }

            return true;
        }

        void FInit()
        {
            FInitSherlock();
        }

        private void ShowInspectCount(double dPass, double dFail)
        {
            double dTotal;
            double dPassPersent;

            //textBox_CheckPassCount.Text = dPass.ToString();
            //textBox_CheckFailCount.Text = dFail.ToString();
            setText_TextBox(textBox_OKCount, dPass.ToString());
            setText_TextBox(textBox_NGCount, dFail.ToString());

            dTotal = dPass + dFail;
            setText_TextBox(textBox_TotalCount, dTotal.ToString());
            if (dTotal > 0)
            {
                dPassPersent = dPass * 100 / dTotal;
            }
            else
            {
                dPassPersent = 0;
            }
            setText_TextBox(textBox_OKPersent, dPassPersent.ToString("F2") + "%");
        }

        private void Stop()
        {
            IpeEngCtrlLib.I_MODE iCurrMode;

            m_iReturn = m_VisionSystem.InvModeSet(IpeEngCtrlLib.I_MODE.I_EXE_MODE_HALT); // halt inspection after current inspection is finished
            m_iReturn = m_VisionSystem.InvModeGet(out iCurrMode);

            int iLoopCount = 0;

            while (iCurrMode != IpeEngCtrlLib.I_MODE.I_EXE_MODE_HALT && iLoopCount < 20000) //stay in loop until Halt is complete
            {
                iLoopCount++;
                // Thread.Sleep(50);
                Application.DoEvents();
                m_iReturn = m_VisionSystem.InvModeGet(out iCurrMode);
            }
            if (iLoopCount >= 20000)
            {
                System.Environment.Exit(0);
            }

            m_bStop = true;
        }

        private void SaveResultCount()
        {
            if (GlobalCfg.m_LogCfg.InspectCount.bSaveCount)
            {
                GlobalCfg.SaveResultCount(textBox_OKCount.Text, textBox_NGCount.Text);
            }
        }

        private void EnableAllWindows(bool bStop)
        {
            if (bStop)
            {
                Menu_Halt.Enabled = false;
                Menu_Continuous.Enabled = true;
            }
            else
            {
                Menu_Halt.Enabled = true;
                Menu_Continuous.Enabled = false;
            }

            bool bEnabled = bStop;

            Menu_InspectOnce.Enabled = bEnabled;
            Menu_SherlockCfg.Enabled = bEnabled;
            Menu_SaveSherlockAs.Enabled = bEnabled;
            Menu_SaveSherlock.Enabled = bEnabled;
            if (bEnabled == true)
            {
                if (GlobalCfg.m_OperatorCfg.bLogIn == true)
                {
                }
                else
                {
                    bEnabled = false;
                }
            }


            Menu_LogCfg.Enabled = bEnabled;

            Menu_SaveNGPic.Enabled = bEnabled;
            Menu_SaveOKPic.Enabled = bEnabled;
            button_ResetCheckResult.Enabled = bEnabled;
            checkBox_RstRoi.Enabled = bEnabled;
            comboBox_ROI.Enabled = bEnabled;
        }



        private void timer_OneSecond_Tick(object sender, EventArgs e)
        {
            TimeSpan ts2 = m_SysRunTime.Elapsed;
            textBox_SysRunTime.Text = ts2.ToString();
        }

        private void GUI_Load(object sender, EventArgs e)
        {
            GlobalCfg.m_UserValues.m_GUI = this;

            m_LoadShowDlg.Show();

            Init();

            m_LoadShowDlg.Close();

        }

        private void GUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            FInit();
        }

        private void GUI_SizeChanged(object sender, EventArgs e)
        {
            if (m_bInit == true)
            {
                axIpeDspCtrl_Sherlock.SetZoom(GlobalCfg.m_SherlockCfg.dPicZoom);// set display zoom to stretch
            }
        }

        private void Menu_SherlockCfg_Click(object sender, EventArgs e)
        {
            SherlockCfgDlg dlg = new SherlockCfgDlg();
            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.ShowDialog();

            if (dlg.DialogResult == DialogResult.OK)
            {
                if (dlg.textBox_SherlockPath.Text != GlobalCfg.m_SherlockCfg.strProgramPath)
                {
                    GlobalCfg.m_SherlockCfg.strProgramPath = dlg.textBox_SherlockPath.Text;

                    FInitSherlock();
                    InitSherlock();
                }
                else
                {
                    axIpeDspCtrl_Sherlock.SetZoom(GlobalCfg.m_SherlockCfg.dPicZoom);// set display zoom to stretch
                }

                GlobalCfg.SaveSherlockCfg();
            }
        }

        private void Menu_LogCfg_Click(object sender, EventArgs e)
        {
            LogCfgDlg dlg = new LogCfgDlg();
            dlg.StartPosition = FormStartPosition.CenterScreen;

            dlg.ShowDialog();

            Menu_SaveNGPic.Checked = GlobalCfg.m_LogCfg.PicLogCfg_NG.bSavePic;
            Menu_SaveOKPic.Checked = GlobalCfg.m_LogCfg.PicLogCfg_OK.bSavePic;
        }

        private void MenuItem_LogIn_Click(object sender, EventArgs e)
        {
            LogInDlg dlg = new LogInDlg();
            dlg.ShowDialog();

            EnableAllWindows(m_bStop);
        }

        private void MenuItem_LogOut_Click(object sender, EventArgs e)
        {
            GlobalCfg.m_OperatorCfg.bLogIn = false;
            EnableAllWindows(m_bStop);
        }

        private void Menu_InspectOnce_Click(object sender, EventArgs e)
        {
            m_iReturn = m_VisionSystem.InvModeSet(IpeEngCtrlLib.I_MODE.I_EXE_MODE_ONCE);
            checkBox_RstRoi.Checked = false;
        }

        private void Menu_Continuous_Click(object sender, EventArgs e)
        {
            EnableAllWindows(false);
            checkBox_RstRoi.Checked = false;
            m_bStop = false;


            m_iReturn = m_VisionSystem.InvModeSet(IpeEngCtrlLib.I_MODE.I_EXE_MODE_CONT);
        }

        private void Menu_Halt_Click(object sender, EventArgs e)
        {
            //
            EnableAllWindows(true);

            Stop();
        }

        private void Menu_SaveSherlock_Click(object sender, EventArgs e)
        {
            SysLog.WriteInfoLog("GUI", "button_Save_Click");

            m_iReturn = m_VisionSystem.InvSave(GlobalCfg.m_SherlockCfg.strProgramPath);
            if (m_iReturn == IpeEngCtrlLib.I_ENG_ERROR.I_OK)
            {
                MessageBox.Show("保存成功");
            }
            else
            {
                MessageBox.Show("保存失败，请重试");
            }
        }

        private void Menu_SaveSherlockAs_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Sherlock (*.ivs)|*.ivs";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SysLog.WriteInfoLog("GUI", "button_Save_Click");

                m_iReturn = m_VisionSystem.InvSave(saveFileDialog1.FileName);
                if (m_iReturn == IpeEngCtrlLib.I_ENG_ERROR.I_OK)
                {
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("保存失败，请重试");
                }
            }
        }

        private void Menu_SaveOKPic_Click(object sender, EventArgs e)
        {
            Menu_SaveOKPic.Checked = !Menu_SaveOKPic.Checked;

            GlobalCfg.m_LogCfg.PicLogCfg_OK.bSavePic = Menu_SaveOKPic.Checked;

            GlobalCfg.SaveLogCfg();
        }

        private void Menu_SaveNGPic_Click(object sender, EventArgs e)
        {
            Menu_SaveNGPic.Checked = !Menu_SaveNGPic.Checked;

            GlobalCfg.m_LogCfg.PicLogCfg_NG.bSavePic = Menu_SaveNGPic.Checked;

            GlobalCfg.SaveLogCfg();
        }

        private void button_ResetCheckResult_Click(object sender, EventArgs e)
        {
            m_iReturn = m_VisionSystem.VarSetDouble("dOKCount_Out", 0);
            m_iReturn = m_VisionSystem.VarSetDouble("dNGCount_Out", 0);

            ShowInspectCount(0, 0);

            GlobalCfg.SaveResultCount(textBox_OKCount.Text, textBox_NGCount.Text);
        }

        private void checkBox_RstRoi_Click(object sender, EventArgs e)
        {

        }

        private void axIpeDspCtrl_Sherlock_MouseMoveEvent(object sender, AxIpeDspCtrlLib._DIpeDspCtrlEvents_MouseMoveEvent e)
        {
            if (checkBox_RstRoi.Checked == true && m_bLButtonDown == true)
            {
                string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];

                m_VisionSystem.RoiCoordSet(strRoi, 1, e.x, e.y);
                m_VisionSystem.SoImageUpdate(GlobalCfg.m_SherlockCfg.strImgWindowsName);
                axIpeDspCtrl_Sherlock.UpdateDisplay();
            }
        }

        private void axIpeDspCtrl_Sherlock_LButtonDown(object sender, AxIpeDspCtrlLib._DIpeDspCtrlEvents_LButtonDownEvent e)
        {
            if (checkBox_RstRoi.Checked == true)
            {
                string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];
                m_bLButtonDown = true;

                m_VisionSystem.RoiCoordSet(strRoi, 0, e.x, e.y);
                m_VisionSystem.RoiCoordSet(strRoi, 1, e.x + 1, e.y + 1);
                m_VisionSystem.SoImageUpdate(GlobalCfg.m_SherlockCfg.strImgWindowsName);
                axIpeDspCtrl_Sherlock.UpdateDisplay();
            }
        }

        private void axIpeDspCtrl_Sherlock_LButtonUp(object sender, AxIpeDspCtrlLib._DIpeDspCtrlEvents_LButtonUpEvent e)
        {
            if (checkBox_RstRoi.Checked == true)
            {
                string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];
                m_bLButtonDown = false;

                m_VisionSystem.RoiCoordSet(strRoi, 1, e.x, e.y);
                m_VisionSystem.SoImageUpdate(GlobalCfg.m_SherlockCfg.strImgWindowsName);
                axIpeDspCtrl_Sherlock.UpdateDisplay();
            }
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];

            if (e.Type == ScrollEventType.SmallIncrement)
            {
                m_VisionSystem.RoiMove(strRoi, 1, 0);
            }
            else if (e.Type == ScrollEventType.SmallDecrement)
            {
                m_VisionSystem.RoiMove(strRoi, -1, 0);
            }

            axIpeDspCtrl_Sherlock.UpdateDisplay();
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];

            if (e.Type == ScrollEventType.SmallIncrement)
            {
                m_VisionSystem.RoiMove(strRoi, 0, 1);
            }
            else if (e.Type == ScrollEventType.SmallDecrement)
            {
                m_VisionSystem.RoiMove(strRoi, 0, -1);
            }

            axIpeDspCtrl_Sherlock.UpdateDisplay();
        }

        private void OnButtonZoom(int iZoom)
        {

            string strRoi = m_strROINameList_Sherlock[comboBox_ROI.SelectedIndex];
            int x = 0, y = 0;
            int iCenter_X = 0, iCenter_Y = 0;
            m_VisionSystem.RoiCoordGet(strRoi, 0, out iCenter_X, out iCenter_Y);
            m_VisionSystem.RoiCoordGet(strRoi, 1, out x, out y);
            if (iCenter_X > x)
            {
                iZoom = 0 - iZoom;
            }

            m_VisionSystem.RoiCoordSet(strRoi, 1, x, y + iZoom);
            m_VisionSystem.SoImageUpdate(GlobalCfg.m_SherlockCfg.strImgWindowsName);
            axIpeDspCtrl_Sherlock.UpdateDisplay();
        }
        private void button_ZoomOut_Click(object sender, EventArgs e)
        {
            OnButtonZoom(1);
        }

        private void button_ZoomIn_Click(object sender, EventArgs e)
        {
            OnButtonZoom(-1);
        }
    }
}
